#include "rclcpp/rclcpp.hpp"
#include "nav_msg_pkg/srv/cancel_task.hpp"

using nav_msg_pkg::srv::CancelTask;

class CancelTaskCLient : public rclcpp::Node
{
public:
    CancelTaskCLient() : Node("cancel_task_client")
    {
        RCLCPP_INFO(this->get_logger(), "cancel_task_client 节点已经启动!");
        cancel_client_ = this->create_client<CancelTask>("cancel_task");
    }
    // 连接服务器
    bool connect_server()
    {
        while (!cancel_client_->wait_for_service(std::chrono::seconds(1)))
        {
            // 对 ctrl + c 退出程序
            if (!rclcpp::ok())
            {
                RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "退出！");
                return false;
            }
            RCLCPP_INFO(this->get_logger(), "等待服务器启动...");
        }
        return true;
    }
    // 发送请求
    rclcpp::Client<CancelTask>::FutureAndRequestId send_request(std::string id)
    {
        auto request = std::make_shared<CancelTask::Request>();
        request->id = id;
        auto result_future = cancel_client_->async_send_request(request);
        return result_future;
    }

private:
    rclcpp::Client<CancelTask>::SharedPtr cancel_client_;
};

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "请输入取消任务id");
        return -1;
    }
    /* 初始化rclcpp  */
    rclcpp::init(argc, argv);
    /* 产生一个 节点 */
    auto client = std::make_shared<CancelTaskCLient>();
    // 判断连接服务器
    bool connect_flag = client->connect_server();
    if (!connect_flag)
    {
        RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "服务未启动!");
        return 0;
    }
    // 发送请求
    auto future = client->send_request(argv[1]);
    if (future.valid())
    {
        RCLCPP_INFO(client->get_logger(), "请求已发送，等待响应...");
        if (rclcpp::spin_until_future_complete(client, future) == rclcpp::FutureReturnCode::SUCCESS)
        {
            RCLCPP_INFO(client->get_logger(), "收到响应...");
            try
            {
                auto result = future.get();
                RCLCPP_INFO(client->get_logger(), "响应结果: code=%d, message=%s",
                            result->response.code,
                            result->response.message.c_str());
            }
            catch (const std::future_error &e)
            {
                RCLCPP_ERROR(client->get_logger(), "请求失败: %s", e.what());
            }
        }
        else
        {
            RCLCPP_ERROR(client->get_logger(), "请求失败!");
        }
    }
    else
    {
        RCLCPP_ERROR(client->get_logger(), "请求发送失败!");
    }
    /* 停止运行 */
    rclcpp::shutdown();
    return 0;
}